import {
  responseWhiteList,
  needSignList,
} from "./config.js";
import { getToken, removeToken,getUserinfo, removeUserinfo, showToast } from "./common.js";
import { paramSignature } from "./signature.js";

let apiUrl = import.meta.env.VITE_API_URL;
// ====响应拦截====
// 刷新锁
let refreshLock = false;

function lockRequest() {
  console.log("lockRequest");
  if (refreshLock) {
    return false;
  }
  refreshLock = true;
  console.log("跳转登录页");
  uni.navigateTo({
    animationType: "pop-in",
    url: "/pages/login/login",
  });
  showToast("请重新登录",true)
  setTimeout(() => {
    uni.$emit("index-collection-list")
    removeToken();
    removeUserinfo();
    // 刷新锁
    refreshLock = false;
  }, 1500);
}

function request({
  url,
  method = "GET",
  responseType = "text",
  data,
  noLoading = false,
  header = {},
  noBase = false,
}) {
  if (method.toLowerCase() == "post") {
    header["Content-type"] = header["Content-type"]
      ? header["Content-type"]
      : "application/x-www-form-urlencoded";
  } else {
    header["Content-type"] = header["Content-type"]
      ? header["Content-type"]
      : "application/json;charset=utf-8";
  }
  let token = getToken();
  let requestUrl = "";
  // #ifdef H5
  let env = import.meta.env;
  if (env.MODE === "development") {
    // if (!noBase) {
    // 	requestUrl = apiUrl+"/baseapi" + url

    // }
    requestUrl = "/baseapi" + url;
  } else {
    requestUrl = apiUrl + url;
  }
  // #endif
  // #ifndef H5
  requestUrl = apiUrl + url;
  // #endif

  // 参数加密
  if (data) {
    if (needSignList.findIndex((item) => url.indexOf(item) !== -1) !== -1) {
      data.sign = paramSignature(data);
    }
  }
  // console.log("requestUrl=" + requestUrl);
  // console.log("请求参数===");
  // console.log(data);

  const userInfo = getUserinfo();
  // header["Authorization"] ='Basic '+ token
  header["TOKEN"] = token ? "Bearer " + token : "";
  header["TOKEN"] = token ? token : "";
  header["UID"] = userInfo && userInfo.userid ? userInfo.userid : "";
  // if (!noLoading) {
  // 	uni.showLoading({
  // 		title: '加载中',
  // 		mask: true
  // 	});
  // }


  return new Promise((resolve, reject) => {
    uni.request({
      method,
      url: requestUrl,
      data,
      header,
      responseType,
      success: (res) => {
        // console.log(res);
        if (res.data.code === 0) {
          // if (!noLoading) {
          // 	uni.hideLoading()
          // }
          resolve(res.data);
        } else {
          // uni.hideLoading()
          if (res.data.code === 403 || res.data.code === 301) {
            console.log("未登录或者登陆已过期");
            lockRequest();
            reject(res.data);
          } else if (
            responseWhiteList.findIndex((item) => url.indexOf(item) !== -1) !==
            -1
          ) {
            // 白名单内直接返回
            resolve(res.data);
          } else if (res.data.code === 23001) {
            reject(res.data);
          } else {
            if (res.data.info) {
              showToast(res.data.info);
            }
            reject(res.data);
          }
        }
      },
      fail: (error) => {
        // uni.hideLoading()
        showToast("REQUEST ERROR");
        console.log("REQUEST ERROR");
        console.log(error);
        reject(error);
      },
    });
  });
}

export default request;
